package com.example.wisdomclassroomapi.facade.security;

import com.alibaba.fastjson.JSON;
import com.example.wisdomclassroomapi.common.cache.RedisCache;
import com.example.wisdomclassroomapi.common.dto.ResponseDto;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功
 */
@Component
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {
    @Resource
    private RedisCache redisCache;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        ResponseAuthenticationDetails details = (ResponseAuthenticationDetails) authentication.getDetails();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(JSON.toJSONString(ResponseDto.success(details)));

        redisCache.setCacheObject(details.getId(), SecurityContextHolder.getContext().getAuthentication());
    }
}
